package org.microframework.base.core.datasource;

import lombok.extern.slf4j.Slf4j;
import javax.sql.DataSource;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.logging.Logger;

/**
 * JFinal数据源代理
 * 包装原始数据源，用于JFinal的事务管理
 */
@Slf4j
public class DataSourceProxy implements DataSource {
    
    private final DataSource originalDataSource;
    
    public DataSourceProxy(DataSource dataSource) {
        this.originalDataSource = dataSource;
        log.info("初始化JFinal数据源代理");
    }
    
    /**
     * 获取连接
     * 这里可以根据需要对连接进行处理
     */
    @Override
    public Connection getConnection() throws SQLException {
        return originalDataSource.getConnection();
    }
    
    /**
     * 获取带用户名密码的连接
     */
    @Override
    public Connection getConnection(String username, String password) throws SQLException {
        return originalDataSource.getConnection(username, password);
    }
    
    @Override
    public PrintWriter getLogWriter() throws SQLException {
        return originalDataSource.getLogWriter();
    }
    
    @Override
    public void setLogWriter(PrintWriter out) throws SQLException {
        originalDataSource.setLogWriter(out);
    }
    
    @Override
    public void setLoginTimeout(int seconds) throws SQLException {
        originalDataSource.setLoginTimeout(seconds);
    }
    
    @Override
    public int getLoginTimeout() throws SQLException {
        return originalDataSource.getLoginTimeout();
    }
    
    @Override
    public Logger getParentLogger() throws SQLFeatureNotSupportedException {
        return originalDataSource.getParentLogger();
    }
    
    @SuppressWarnings("unchecked")
	@Override
    public <T> T unwrap(Class<T> iface) throws SQLException {
        if (iface.isInstance(this)) {
            return (T) this;
        }
        return originalDataSource.unwrap(iface);
    }
    
    @Override
    public boolean isWrapperFor(Class<?> iface) throws SQLException {
        return (iface.isInstance(this) || originalDataSource.isWrapperFor(iface));
    }
    
    /**
     * 获取原始数据源
     */
    public DataSource getOriginalDataSource() {
        return originalDataSource;
    }
} 